package server

import (
	"5-19yk/common/models/mysql"
	"5-19yk/common/models/redis"
	"5-19yk/common/pkg"
	"5-19yk/common/proto/doctor"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	jwt "github.com/golangblogs/gojwt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"math/rand"
	"strconv"
	"time"
)

func SendSms(req *doctor.SendSmsReq) (*doctor.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	val := redis.Rdb.Set(context.Background(), "sendSms"+req.SouRes+req.Phone, code, time.Minute*30).Val()
	return &doctor.SendSmsResp{SendSms: val}, nil
}

func Login(req *doctor.LoginReq) (*doctor.LoginResp, error) {
	val := redis.Rdb.Get(context.Background(), "sendSmslogin"+req.Phone).Val()
	if val != req.SendCode {
		return nil, errors.New("验证码错误")
	}
	user, err := mysql.GetUser(req.Phone)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if user.Phone == "" {
		m := mysql.User{
			Model:    gorm.Model{},
			Name:     req.Name,
			Phone:    req.Phone,
			Password: req.Password,
			Email:    req.Email,
		}
		err := mysql.CreateUser(&m)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if req.Password != user.Password {
		return nil, errors.New("密码错误")
	}
	claims := jwt.CustomClaims{ID: user.ID}
	token, err := jwt.NewJWT("2210a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}
	return &doctor.LoginResp{Success: token}, nil
}

func HospitalList(req *doctor.HospitalListReq) (*doctor.HospitalListResp, error) {
	list, err := mysql.HospitalList(int(req.Page), int(req.Size), req.HospitalName)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var Lists []*doctor.List
	for _, i := range list {
		d := &doctor.List{
			HospitalName:     i.HospitalName,
			HospItalInter:    i.HospItalInter,
			HospItalAddress:  i.HospItalAddress,
			HospitalType:     i.HospitalType,
			HospitalImage:    i.HospitalImage,
			HospitalFeaTrues: i.HospitalFeaTrues,
		}
		Lists = append(Lists, d)
		marshal, err := json.Marshal(Lists)
		if err != nil {
			return nil, errors.New("解析失败")
		}
		sprintf := fmt.Sprintf("HospitalList:%d:%d", req.Page, req.Size)
		redis.Rdb.Set(context.Background(), sprintf, marshal, time.Minute*30)
	}
	return &doctor.HospitalListResp{List: Lists}, nil
}

func DepartmentList(req *doctor.DepartmentListReq) (*doctor.DepartmentListResp, error) {
	list, err := mysql.DepartmentList(int(req.Page), int(req.Size), req.HospitalName)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*doctor.DepartmentList
	for _, department := range list {
		lists = append(lists, &doctor.DepartmentList{
			HospitalId:     int64(department.HospitalId),
			FId:            int64(department.FId),
			DepartmentName: department.DepartmentName,
		})
	}
	return &doctor.DepartmentListResp{List: lists}, nil
}

func PatientList(req *doctor.PatientListReq) (*doctor.PatientListResp, error) {
	list, err := mysql.PatientList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*doctor.PatientList
	for _, patient := range list {
		lists = append(lists, &doctor.PatientList{
			UserId:      int64(patient.UserId),
			PatientName: patient.PatientName,
		})
	}
	return &doctor.PatientListResp{List: lists}, nil
}
func DoctorList(req *doctor.DoctorListReq) (*doctor.DoctorListResp, error) {
	list, err := mysql.DoctorList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*doctor.DoctorList
	for _, patient := range list {
		lists = append(lists, &doctor.DoctorList{
			DepartmentId:    int64(patient.DepartmentId),
			HospitalId:      int64(patient.HospitalId),
			DocTorName:      patient.DocTorName,
			BeOnDutyTimeSta: patient.BeOnDutyTimeSta,
			BeOnDutyTimeEnd: patient.BeOnDutyTimeEnd,
		})
	}
	return &doctor.DoctorListResp{List: lists}, nil
}

func OrderCreate(req *doctor.OrderCreateReq) (*doctor.OrderCreateResp, error) {
	show, err := mysql.UserShow(int(req.UserId))
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	patientShow, err := mysql.PatientShow(int(req.PatientId))
	if err != nil {
		return nil, errors.New("就诊人查询失败")
	}
	torShow, err := mysql.DocTorShow(int(req.DocTorId))
	if err != nil {
		return nil, errors.New("医生查询失败")
	}
	departmentShow, err := mysql.DepartmentShow(int(req.HospitalId))
	if err != nil {
		return nil, errors.New("科室查询失败")
	}
	hospital, err := mysql.HospitalShow(int(req.HospitalId))
	if err != nil {
		return nil, errors.New("医院查询失败")
	}
	newString := uuid.NewString()
	order := mysql.Order{
		Model:        gorm.Model{},
		DepartmentId: int(departmentShow.ID),
		UserId:       int(show.ID),
		DocTorId:     int(torShow.ID),
		HospitalId:   int(hospital.ID),
		PatientId:    int(patientShow.ID),
		OrderSn:      newString,
		Price:        torShow.DocTorPrice,
		Status:       1,
	}
	if torShow.DocTorInventory <= 0 {
		return nil, errors.New("库存不足")
	}
	err = mysql.CreateOrder(&order)
	if err != nil {
		return nil, errors.New("订单创建失败")
	}
	float := strconv.FormatFloat(torShow.DocTorPrice, 'f', 2, 64)
	pay := pkg.ALiPay("预约费用", newString, float)
	return &doctor.OrderCreateResp{
		Url:     pay,
		OrderSn: newString,
	}, nil
}
func OrderList(req *doctor.OrderListReq) (*doctor.OrderListResp, error) {
	list, err := mysql.OrderList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*doctor.OrderList
	for _, patient := range list {
		lists = append(lists, &doctor.OrderList{
			DepartmentId: int64(patient.DepartmentId),
			UserId:       int64(patient.UserId),
			DocTorId:     int64(patient.DocTorId),
			HospitalId:   int64(patient.HospitalId),
			PatientId:    int64(patient.PatientId),
			OrderSn:      patient.OrderSn,
			Price:        float32(patient.Price),
		})
	}
	return &doctor.OrderListResp{List: lists}, nil
}
